/**
 * Copyright 2009 Henning Teek, Ingo Renner
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.bricket.plugin.user.web;

import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.feedback.ContainerFeedbackMessageFilter;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.target.basic.RedirectRequestTarget;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.odlabs.wiquery.core.javascript.JsScope;
import org.odlabs.wiquery.core.options.ListItemOptions;
import org.odlabs.wiquery.ui.dialog.Dialog;
import org.odlabs.wiquery.ui.dialog.DialogButton;

import brix.web.nodepage.PageParametersCarryingLink;

import com.googlecode.bricket.plugin.user.domain.User;
import com.googlecode.bricket.plugin.user.repository.UserService;
import com.googlecode.bricket.web.BricketFeedbackPanel;
import com.googlecode.bricket.web.WicketApplication;
import com.googlecode.bricket.web.WicketWebSession;
import com.googlecode.bricket.web.auth.LoginPage;

/**
 * @author Henning Teek
 */
public class UserPanel extends Panel {
	@SpringBean
	UserService userService;

	private BricketFeedbackPanel bricketFeedback;
	
	private boolean initFinished;

	private SettingsForm form;

	private FeedbackPanel feedback;

	private Dialog dialog;

	private AccountPanel accountPanel;

	public UserPanel(String id) {
		super(id);
		
        boolean signedIn = ((WicketWebSession)getSession()).isSignedIn();
		User user = signedIn ? ((WicketWebSession)getSession()).getUser() : null;

		form = new SettingsForm("form", new CompoundPropertyModel<User>(((WicketWebSession) getSession()).getUser()));
        form.setOutputMarkupId(true);

		dialog = new Dialog("dialog");
		dialog.add(form);
        
        feedback = new FeedbackPanel("feedback", new ContainerFeedbackMessageFilter(form));
        feedback.setOutputMarkupPlaceholderTag(true);
        dialog.add(feedback);

        add(dialog);

        AjaxLink<String> openDialog = new AjaxLink<String>("settingsLink") {
            @Override
            public void onClick(AjaxRequestTarget target) {
            		form = new SettingsForm("form", new CompoundPropertyModel<User>(((WicketWebSession) getSession()).getUser()));
            		dialog.addOrReplace(form);
            		target.addComponent(form);
            		dialog.open(target);
            }
	    };
	    openDialog.add(new Label("greeting", user != null ? new StringResourceModel("greeting", new Model<User>(user)) : new Model<String>("")));
	    add(openDialog);

    	add(new Link<Void>("siteadminLink") {
			@Override
			public void onClick() {
				getRequestCycle().setRequestTarget(new RedirectRequestTarget("/admin"));
			}
		}.setVisible(signedIn && user.isAdmin()));

    	add(new Link<Void>("logoutLink") {
			@Override
			public void onClick() {
				getSession().invalidate();
				getRequestCycle().setRequestTarget(new RedirectRequestTarget("/"));
			}
		}.setVisible(signedIn));
		
		add(new BookmarkablePageLink<LoginPage>("loginLink", LoginPage.class).setVisible(!signedIn));
		add(new PageParametersCarryingLink("signupLink", ((WicketApplication)getApplication()).getI18nBrixLink(getSession(), "/signup.html")));
	}

	@Override
	protected void onBeforeRender() {
		super.onBeforeRender();
		 if (!hasBeenRendered()) {
			 init();
		 }
	}

	private void init() {
		if (!initFinished) {
			this.bricketFeedback = ((WicketApplication) getApplication()).getBricketFeedbackPanel(UserPanel.this.getPage());
			
			AbstractDefaultAjaxBehavior formAjaxBehavior = new AbstractDefaultAjaxBehavior() {
	            @Override
	            protected void respond(AjaxRequestTarget target) {
	                    // Here, we retrieve data form the form of the advanced dialog
	                    form.onFormSubmitted();
	                    
	                    if(form.hasError()){
	                            // Error
	                            target.addComponent(feedback);
	                    } else {
	                            getSession().cleanupFeedbackMessages();
	            				accountPanel.processPassword();
	            				userService.saveUser(form.getModelObject());
	            				getSession().info("Einstellungen erfolgreich gespeichert.");
	            				target.addComponent(bricketFeedback);
	                            dialog.close(target);
	                    }
	            }
	        };
	    	add(formAjaxBehavior);

	    	ListItemOptions<DialogButton> buttonsAdv = new ListItemOptions<DialogButton>();
	        buttonsAdv.add(new DialogButton(new StringResourceModel("cancel.label", UserPanel.this, null).getString(), 
	        		JsScope.quickScope(dialog.close().render())));
	        buttonsAdv.add(new DialogButton(new StringResourceModel("create.label", UserPanel.this, null).getString(), 
	        		JsScope.quickScope("wicketSubmitFormById('" + form.getMarkupId() + "','" + 
	        		formAjaxBehavior.getCallbackUrl() + "', null, null, null, null, null);")));
	        dialog.setButtons(buttonsAdv);
	        dialog.setTitle(new StringResourceModel("settings.headline", UserPanel.this, null).getString());
	        dialog.setCloseOnEscape(false);
	        dialog.setModal(true);
	        dialog.setHeight(450);
	        dialog.setWidth(520);
		}
		initFinished = true;
	}

	class SettingsForm extends Form<User> {
		public SettingsForm(String id, IModel<User> model) {
			super(id, model);

			accountPanel = new AccountPanel("account", getModel(), SettingsForm.this);
			add(accountPanel);
		}
	}
}
